import { useState } from "react";

interface Message {
  id: number;
  role: "user" | "ai";
  content: string;
}

function ChatPage() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");

const handleSend = async () => {
  if (!input.trim()) return;

  const userMessage: Message = {
    id: Date.now(),
    role: "user",
    content: input,
  };
  setMessages((prev) => [...prev, userMessage]);
  const question = input;
  setInput("");

  try {
    const response = await fetch("http://localhost:5552/api/chat/send_text", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        "question": question,
        "route": "example_route"
      }),
    });
    const res = await response.json();
    console.log("res:", res);
    if (!res.success) {
      console.log("err_msg:", res?.err_msg);
      return;
    }

    const aiMessage: Message = {
      id: Date.now() + 1,
      role: res.reply.role,
      content: res.reply.data,
    };

    setMessages((prev) => [...prev, aiMessage]);
  } catch (err) {
    console.log("err_msg:", err);
  }
};

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      handleSend();
    }
  };

  return (
    <div style={{ padding: "20px", maxWidth: "600px", margin: "0 auto" }}>
      <h2>AI 聊天页面</h2>

      {/* 消息列表 */}
      <div
        style={{
          border: "1px solid #ccc",
          borderRadius: "8px",
          padding: "10px",
          height: "400px",
          overflowY: "auto",
          display: "flex",
          flexDirection: "column",
          gap: "10px",
          backgroundColor: "#f9f9f9",
        }}
      >
        {messages.map((msg) => (
          <div
            key={msg.id}
            style={{
              alignSelf: msg.role === "user" ? "flex-end" : "flex-start",
              backgroundColor: msg.role === "user" ? "#007bff" : "#e5e5e5",
              color: msg.role === "user" ? "#fff" : "#000",
              padding: "8px 12px",
              borderRadius: "16px",
              maxWidth: "70%",
              wordBreak: "break-word",
            }}
          >
            {msg.content}
          </div>
        ))}
      </div>

      {/* 输入框 */}
      <div style={{ marginTop: "10px", display: "flex", gap: "8px" }}>
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyPress}
          placeholder="输入消息，回车发送"
          style={{ flex: 1, padding: "8px", borderRadius: "4px", border: "1px solid #ccc" }}
        />
        <button
          onClick={handleSend}
          style={{
            padding: "8px 16px",
            borderRadius: "4px",
            border: "none",
            backgroundColor: "#007bff",
            color: "#fff",
            cursor: "pointer",
          }}
        >
          发送
        </button>
      </div>
    </div>
  );
}

export default ChatPage;
